package com.jike.mahjong.task;

import com.google.gson.Gson;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.common.util.HttpUtil;
import com.jike.mahjong.model.RequestMethod;
import com.jike.mahjong.model.RequestModel;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

/**
 * Created by star on 2016/12/27.
 */
public class MsgTask extends TimerTask {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    private String content;



    public MsgTask(String content) {
        this.content = content;
    }

    public void setPeriod(long period) {
        //缩短周期，执行频率就提高

    }

    public  void setNxtExecutionTime(long period,long nextExecutionTime) {
        setDeclaredField(TimerTask.class, this, "nextExecutionTime", nextExecutionTime);
        setDeclaredField(TimerTask.class, this, "period", period);
    }

    //通过反射修改字段的值
    public static boolean setDeclaredField(Class<?> clazz, Object obj,
                                           String name, Object value) {
        try {
            Field field = clazz.getDeclaredField(name);
            field.setAccessible(true);
            field.set(obj, value);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    @Override
    public void run() {
        List<String> args = new ArrayList<String>();
        RequestModel requestModel = new RequestModel();
        requestModel.setCmd(RequestMethod.sendNotice);
        args.add(content);
        requestModel.setArgs(args);
        System.out.println(content + sdf.format(new Date()));
        Gson gson = new Gson();
        String paraStr = gson.toJson(requestModel);
        String result = HttpUtil.PostWithJson(Constants.BACK_URL, paraStr);
        System.out.println(result);
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

